// pages/consultationList/index.js
import {
  ApiGetMessageRecord,
  ApiCompleteOrder,
  ApiRefund,
  ApiGetOrderInfo,
  ApiChangeGroup,
  ApiAdviceRollback,
  ApigetReplyTemplate,
  ApigetReplyTemplateDelete
} from "../../api/docIndex.js"
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showpopup: false,
    videoData: {
      icon: 'phone-circle-o',
      text: '视频'
    },
    baseData: [{
        icon: 'photo-o',
        text: '图片'
      }, {
        icon: 'gold-coin-o',
        text: '退款'
      },
      {
        icon: 'bookmark-o',
        text: '病历'
      },
      {
        icon: 'balance-list-o',
        text: '处方'
      }, {
        icon: 'phone-circle-o',
        text: '视频'
      },
      /*    , {
           icon: 'credit-pay',
           text: '开具检查单'
         } */
    ],
    baseUrl: app.globalData.$path,
    offsetTop: 0,
    contact: {},
    userInfo: {},
    message: "",
    list: [],
    loading: false,
    finish: false,
    showIcon: false,
    showFooter: true,
    commonExpressions: false,
  },
  endFlag: false, //是否在底部,
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {

    this.setData({
      loginType: wx.getStorageSync('loginType')
    })
  },
  //添加常用语
  addContent() {
    wx.navigateTo({
      url: '/pagesDoctor/contentAdd/index',
    })
  },
  //编辑常用语
  editContent(e) {
    console.log(e)
    let val = e.currentTarget.dataset.v
    wx.navigateTo({
      url: `/pagesDoctor/contentAdd/index?data=${JSON.stringify(val)}`,
    })
  },
  //删除常用语
  delContent(e) {
    let that = this
    wx.showModal({
      title: "是否确认删除该数据？",
      success(res) {
        if (res.confirm) {
          ApigetReplyTemplateDelete(e.currentTarget.dataset.v.id).then((res) => {
            if (res.code == '200') {
              wx.showToast({
                title: "删除成功",
              })
              that.getReplyTemplate()
            }

          })
        }

      }
    })
  },
  clickContent(e) {
    let text = e.currentTarget.dataset.v
    this.setData({
      message: text
    })
  },


  getReplyTemplate() {
    ApigetReplyTemplate({
      page: '1',
      size: '999'
    }).then(res => {
      this.setData({
        contentArr: res.data
      })
    })
  },
  //再次问诊的事件
  /*   askAgain() {
      const today = new Date();
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从0开始，因此要加1
      const day = String(today.getDate()).padStart(2, '0'); // 保证日期是两位数
      wx.navigateTo({
        url: `/pages/doctorDetails/index?id=${this.data.contact.doctor_id}&&date=${year}-${month}-${day}&&index1=0`,
      })
    }, */



  onShow() {

    /*       this.getMessageList() */
    this.data.list = []
    app.setWsIsClose(true)
    //返回评价的数据
    let pages = getCurrentPages();
    let currPage = pages[pages.length - 1];
    this.setData({
      contact: wx.getStorageSync('messageDetail'),
      'contact.cancel_time': currPage.data.cancelcomment,
      userInfo: wx.getStorageSync('userInfo')
    })
    app.ws.onRoom(this.data.contact.consultation_order_id, this.acceptMessage.bind(this))
    // 打开服务器
    app.ws.send({
      action: 'openPage',
      consultation_order_id: this.data.contact.consultation_order_id
    })

    if (!this.data.contact.finish_time) {
      if (this.data.contact.statusS && this.data.contact.statusS == '未开始') {
        wx.showModal({
          title: '提示',
          content: `您的就诊时间段为:${this.data.contact.order_time}，当前还未到就诊时间段，医生回复消息可能不及时`,
          icon: 'error',
          showCancel: false
        })
      }
    }
    this.getMessageList()
    //获取患者信息
    this.getOrderInfo()
    this.getReplyTemplate()
    /*  if (currPage.data.infoContact) {
       setTimeout(() => {
         this.sendPrescriptions(currPage.data.infoContact)
       }, 1000);
     } */

  },
  //患者标签
  patientLabel(e) {
    this.setData({
      showFooter: false,
      showPicker: true,
      patient_id: e.currentTarget.dataset.v
    })
  },

  getId(e) {
    ApiChangeGroup({
      patient_id: this.data.patient_id,
      group_id: e.detail
    }).then(res => {
      if (res.code == '200') {
        this.setData({
          showFooter: true
        })
        wx.showToast({
          title: "添加成功",
        })
      }
    })
  },

  getClose() {
    console.log('1111')
    this.setData({
      showFooter: true
    })
  },

  getOrderInfo() {
    ApiGetOrderInfo(this.data.contact.id).then(res => {
      if (res.data.order_type == '图文问诊' || res.data.order_type == '视频问诊') {
        let val = this.data.baseData.find(item => {
          if (item.text == '转号') {
            return item
          }
        })
        if (!val) {
          this.data.baseData.push({
            icon: 'bookmark-o',
            text: '转号'
          })
        }
      }
      if (res.data.order_type == '团队问诊') {
        let val = this.data.baseData.find(item => {
          if (item.text == '会诊报告') {
            return item
          }
        })
        if (!val) {
          this.data.baseData.push({
            icon: 'sign',
            text: '会诊报告'
          })
        }
      }
      if (res.data.order_type == '首诊咨询') {
        let val = this.data.baseData.findIndex(item => {
          if (item.text == '病历') {
            return item
          }
        })
        console.log(val)
        if (val != '-1') {
          this.data.baseData.splice(val, 1)
        }
        let val1 = this.data.baseData.findIndex(item => {
          if (item.text == '处方') {
            return item
          }
        })
        if (val1 != '-1') {
          this.data.baseData.splice(val1, 1)
        }
      }
      this.setData({
        orderInfo: res.data,
        baseData: this.data.baseData
      })
    })
  },

  //处方单明细查询
  handlePreClick(e) {
    this.data.list = []
    /*     console.log(e) */
    let id = e.currentTarget.dataset.v.content.preMessageId
    wx.navigateTo({
      url: `/pagesDoctor/adviceInfoByID/index?id=${id}`,
    })
    /*   ApiAdviceInfoByID(id).then(res=>{

      }) */

  },


  //患者病历查询
  medicalRecordsSearch() {
    wx.navigateTo({
      url: `/pagesDoctor/medicalRecordsSearch/index?patient_id=${this.data.contact.patient_id}`,
    })
  },

  //处方列表
  preRecordsSearch() {
    console.log('e')
    wx.navigateTo({
      url: `/pagesDoctor/prescriptionList/index?order_id=${this.data.contact.id}`,
    })
  },


  /*   sendPrescriptions(val) {
      const contact = this.data.contact
      const parmas = {
        consultation_order_id: contact.consultation_order_id,
        action: "message",
        receiver: contact.doctor_id,
        content: val,
        type: "prescription",
        sender: this.data.userInfo.id,
        sender_type: "doctor",
        id: Date.now()
      }
      app.ws.send(parmas, () => {
        let paramsData = {
          ...parmas,
          sender_icon: wx.getStorageSync('userInfo').icon
        }
        paramsData.content = JSON.parse(paramsData.content)
        this.data.list.push(paramsData)
        console.log(paramsData)
        this.setData({
          message: "",
          list: this.data.list
        }, () => {
          wx.pageScrollTo({
            scrollTop: 999999999
          })
        })
      }, () => {
        wx.showToast({
          title: '发送失败',
          icon: "error"
        })
      })
      /*  this.getMessageList() */



  onHide() {

  },


  onReady() {
    this.endDom = this.createIntersectionObserver({
      thresholds: [0],
    }).relativeToViewport().observe("#end", (res) => {
      this.endFlag = res.intersectionRatio > 0
    })
  },

  acceptMessage(obj) {
    console.log('obj', obj)
    if (this.data.contact.consultation_order_id == obj?.consultation_order_id) {
      console.log('1111')
      this.data.list.push(obj)
      obj.sender_icon = obj.icon
      this.setData({
        list: this.data.list
      }, () => {
        wx.vibrateLong({
          // type: "heavy",
          // complete: (res) => {
          //   console.log('res',res)
          // }
        })
        if (this.endFlag) {
          wx.pageScrollTo({
            scrollTop: 999999999,
          })
        }
      })
    }
  },


  onPageScroll(e) {
    if (this.data.loading || this.data.finish) return
    if (e.scrollTop === 0) {
      this.getMessageList()
    }
  },

  //点击拍照


  getMessageList() {
    this.setData({
      loading: true
    })
    const ops = {
      message_id: this.data.list[0]?.id ?? "",
      size: 20,
    }
    wx.showLoading({
      title: '加载中'
    })
    ApiGetMessageRecord({
      order_id: this.data.contact.id,
      ...ops
    }).then(res => {
      res.data.forEach(item => {
        if (item.type == 'prescription' || item.type == 'patientCard') {
          item.content = JSON.parse(item.content)
        }
      })
      const data = res.data || []
      const finish = !data.length
      const list = data.concat(this.data.list)
      const parmas = {
        finish
      }
      if (!finish) {
        parmas.list = list
      }
      this.setData(parmas, () => {
        if (!finish) {
          if (ops.message_id) {
            wx.pageScrollTo({
              selector: `.message_${ops.message_id}`,
              offsetTop: -100,
              duration: 0,
            })
          } else {
            wx.pageScrollTo({
              scrollTop: 999999999,
              duration: 0,
            })
          }
        }
      })
    }).finally(_ => {
      this.setData({
        loading: false
      })
      wx.hideLoading()
    })
  },

  onHeightchange(e) {
    this.setData({
      offsetTop: e.detail.height,
      showIcon: false,
      commonExpressions: false,
    })
    wx.pageScrollTo({
      selector: '.message_' + (this.data.list[this.data.list.length - 1].id),
      offsetTop: -100, //偏移的位置
      duration: 1,
    });
  },

  onInput(e) {
    const value = e.detail.value
    this.setData({
      message: value,
    })
  },

  onConfirm() {
    if (!this.data.message.trim()) {
      wx.showToast({
        title: '不能发送空白内容！',
        icon: "none"
      })
      this.setData({
        message: ""
      })
      return
    }
    /*   contact={"icon":"files/user/20240924/20240924124038_tRLBCHhdYsmF0b87c30622f9659709a7dd7fd34497be.png","id":72,"doctor_id":5,"doctor_name":"李四","department_name":"消化内科","consultation_order_id":72,"order_time":"2024-12-12 15:17-23:17"} */
    const contact = this.data.contact
    const parmas = {
      consultation_order_id: contact.consultation_order_id,
      action: "message",
      receiver: contact.doctor_id,
      content: this.data.message,
      type: "txt",
      sender: this.data.userInfo.id,
      sender_type: "doctor",
      id: Date.now()
    }
    app.ws.send(parmas, () => {
      let paramsData = {
        ...parmas,
        sender_icon: wx.getStorageSync('userInfo').icon
      }
      this.data.list.push(paramsData)
      this.setData({
        message: "",
        list: this.data.list
      }, () => {
        wx.pageScrollTo({
          scrollTop: 999999999
        })
      })
    }, () => {
      wx.showToast({
        title: '发送失败',
        icon: "error"
      })
    })
  },

  clickData(e) {
    console.log(e)
    let that = this
    let text = e.currentTarget.dataset.v.text
    if (text == '图片') {
      this.openImage()
    }
    if (text == '退款') {
      this.refund()
    }
    if (text == '处方') {
      if (this.data.orderInfo.case_history && this.data.orderInfo.case_history.length == 0) {
        wx.showModal({
          title: "请先开具病历！",
          success(res) {
            if (res.confirm) {
              that.medicalRecords()
            }
          }
        })
      } else {
        this.prescribing()
      }
    }
    if (text == '视频') {
      console.log(this.data.orderInfo.user.openid, wx.getStorageSync('userInfo').openid)

      let that = this

      wx.setEnable1v1Chat({
        enable: true,
        success(res) {
          wx.join1v1Chat({
            listener: { //接入
              nickname: '',
              openid: that.data.orderInfo.user.openid
            },
            caller: { //呼出
              nickname: '',
              openid: wx.getStorageSync('userInfo').openid,
            },
            success(res) {
              const contact = that.data.contact
              const parmas = {
                consultation_order_id: contact.consultation_order_id,
                action: "message",
                receiver: contact.doctor_id,
                content: "视频通话",
                type: "txt",
                sender: that.data.userInfo.id,
                sender_type: "doctor",
                id: Date.now(),
                sender_icon: wx.getStorageSync('userInfo').icon
              }
              app.ws.send(parmas, () => {
                let paramsData = {
                  ...parmas,
                  sender_icon: wx.getStorageSync('userInfo').icon
                }
                that.data.list.push(paramsData)
                that.setData({
                  message: "",
                  list: that.data.list
                }, () => {
                  wx.pageScrollTo({
                    scrollTop: 999999999
                  })
                })
              }, () => {
                wx.showToast({
                  title: '发送失败',
                  icon: "error"
                })
              })
            },
            fail(err) {
              console.log('[startCallWx]err', err)
            }
          })


        },
        fail(err) {

        },
        complete() {

        }
      })





      /*  wx.join1v1Chat({
         caller: {
           nickname: 'c',
           headImage: 'c',
          
         },
         listener: {
           nickname: 'c1',
           headImage: '1',
         
         },
         success(res) {
           console.log('[startCallWx]res', res)
         },
         fail(err) {
           console.log('[startCallWx]err', err)
         }
       }) */
    }
    if (text == '病历') {
      this.medicalRecords()
    }
    if (text == '转号') {
      this.referral()
    }
    if (text == '会诊报告') {
      this.consultationReport()
    }
  },

  //会诊报告
  consultationReport() {
    wx.navigateTo({
      url: `/pagesDoctor/consultationReport/index?orderId=${this.data.contact.id}`,
    })
  },
  //转诊方法
  referral() {
    wx.navigateTo({
      url: `/pagesDoctor/referralDetail/index?orderId=${this.data.contact.id}`,
    })
  },

  //发送图片/
  openImage(e) {
    app.setWsIsClose(false)
    wx.chooseMedia({
      count: 3,
      mediaType: ['image'],
      sizeType: ["compressed", 'original'],
      success: (res) => {
        const contact = this.data.contact
        const data = res.tempFiles.map((item, index) => {
          return {
            consultation_order_id: contact.consultation_order_id,
            action: "message",
            receiver: contact.doctor_id,
            content: "",
            type: "img",
            sender: this.data.userInfo.id,
            sender_type: "doctor",
            id: Date.now() + index,
            file: item.tempFilePath,
            sender_icon: wx.getStorageSync('userInfo').icon
          }
        })
        const list = this.data.list.concat(data)
        /*         app.ws.send(data) */
        setTimeout(() => {
          this.setData({
            message: "",
            list: list
          }, () => {
            wx.pageScrollTo({
              scrollTop: 999999999
            })
          })
        }, 1000);
      },
      complete: () => {
        app.setWsIsClose(true)
      }
    })
  },

  //退款
  refund() {
    this.data.list = []
    // 跳转到退款的界面
    wx.navigateTo({
      url: `/pagesDoctor/cancelRefund/index?orderId=${this.data.contact.id}`,
    })
  },


  prescribing() {
    wx.setStorageSync('preData')
    this.setData({
      showIcon: false
    })
    this.data.list = []

    // 跳转到处方的界面
    wx.navigateTo({
      url: `/pagesDoctor/prescribing/index?orderId=${this.data.contact.id}`,
    })
  },

  medicalRecords() {
    wx.navigateTo({
      url: `/pagesDoctor/medicalRecords/index?orderId=${this.data.contact.id}&patient_gender=${this.data.orderInfo.patient_gender}`,
    })
  },
  /**
   * 生命周期函数--监听页面卸载
   */

  iconClick() {
    this.setData({
      showIcon: !this.data.showIcon,
      commonExpressions: false
    })
    wx.pageScrollTo({
      selector: '#end1',
      offsetTop: 0, //偏移的位置
      duration: 1,
    });
  },


  expressionsClick() {
    this.setData({
      commonExpressions: !this.data.commonExpressions,
      showIcon: false
    })
    wx.pageScrollTo({
      selector: '#end1',
      offsetTop: 0, //偏移的位置
      duration: 1,
    });
  },




  handleClick() {
    this.setData({
      showIcon: false,
      commonExpressions: false
    })
  },


  onUnload() {
    app.ws.send({
      action: 'openPage',
      consultation_order_id: this.data.contact.consultation_order_id
    })
    app.ws.removeRoom(this.data.contact.id)
    this.endDom && this.endDom.disconnect()
  },
  //结束咨询的按钮
  endConsultation() {
    let that = this
    wx.showModal({
      title: "是否确认结束问诊",
      success(res) {
        if (res.confirm) {
          ApiCompleteOrder(that.data.contact.consultation_order_id).then((res) => {
            if (res.code == '200') {
              wx.showToast({
                title: "结束成功",
              })
              /*   contact={"icon":"files/admin/20241129/20241129131303_20241129.jpg","id":43,"doctor_id":1,"doctor_name":"内科医生","department_name":"消化内科","consultation_order_id":58,"status":4,"finish_time":"2024-12-06 09:57:58","comment":null,"statusS":"未开始"} */
              that.setData({
                contact: res.data,
                'contact.consultation_order_id': res.data.id
              })
              /*       setTimeout(() => {
                      wx.navigateBack()
                    }, 500); */
            }

          })
        }

      }
    })

  },
  //立即评价

  evaluatedImmediatel() {
    wx.navigateTo({
      url: `/pages/evaluatedImmediatel/index?doctor_id=${this.data.contact.doctor_id}&&order_id=${this.data.contact.consultation_order_id}`,
    })
  },


  //查看评价
  checkEvaluation() {
    this.data.list = []
    wx.navigateTo({
      url: `/pages/checkEvaluation/index`,
    })
  },

  //获取患者信息
  getPatientInfo() {
    this.data.list = []
    wx.navigateTo({
      url: `/pagesDoctor/patientInfo/index?orderInfo=${JSON.stringify(this.data.orderInfo)}`,
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  // /**
  //  * 用户点击右上角分享
  //  */
  // onShareAppMessage() {

  // }
})